<?php
/**
 * 题库讲评
 */
namespace Admin\Frontend\Controllers;

use Helpers\Tool;
use Helpers\Main;
use Helpers\UserPower;
use Helpers\Template;
use Helpers\Assets;
use Phalcon\Di;
use Phalcon\Db\Column;
use Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter;

class BuyController extends ControllerBase
{
    const Key     = 'xhtest';       //文件服务器key
    const Service = 'buyServiceDB';

    /**
     * 初始化时连接数据库
     *
     * create by zsc 20170503
     */
    protected function initialize()
    {
        error_reporting(E_ERROR);
        self::setDBService();
    }

    /**
     *连接数据库
     *
     * create by zsc 20170503
     */
    public static function setDBService()
    {
        $dbConfig = Main::getConfigByName(self::Service);
        Di::getDefault()->setShared(self::Service, function() use ($dbConfig){
            $connection = new DbAdapter($dbConfig);
            if(APP_DEV){
                $profiler = new \Phalcon\Db\Profiler();
                $eventsManager = new \Phalcon\Events\Manager();
                $logger = new \Phalcon\Logger\Adapter\File(BASE_PATH . "/public/logs/sql.log");
                $eventsManager->attach('db', function($event, $connection) use ($logger, $profiler) {
                    if ($event->getType() == 'beforeQuery') {
                        $profiler->startProfile(
                            $connection->getSQLStatement()
                        );
//                    $variables = $connection->getSQLStatement();
//                    $string = $connection->getSQLVariables();
//                    if ($string) {
//                        $variables .= '['.implode(', ', $string).']';
//                    }
//                    $logger->log($variables, \Phalcon\Logger::INFO);
                    }
                    if ($event->getType() === "afterQuery") {
                        $profiler->stopProfile();
                        $profile = $profiler->getLastProfile();
                        $logger->log(
                            $profile->getSqlStatement(). PHP_EOL .
                            'Time:' . $profile->getTotalElapsedSeconds(), \Phalcon\Logger::INFO);

                    }
                });
                $connection->setEventsManager($eventsManager);
            }

            return $connection;

        });

    }

    /**
     * #方法说明：获取优秀学生列表
     * # Created by zsc
     */
    public function excellentStudentAction(){
        Assets::easyUI('js/buy/excellentStudent.js');
        Assets::fileInput();
        Main::showNavPosition();
        $this->view->setVar('NavUl', '<ul class="breadcrumb"><li><i class="fa fa-home fa-lg"></i> 主页</li><li>购买服务</li><li>优秀学生列表</li></ul>');
        $listButtonArr = $formButtonArr = $listSearchArr = array();
        $listSearchArr[] = ['type'=>'text', 'id'=>'list_search', 'name'=>'list_search', 'label'=>'搜索： '];

            $listButtonArr[] = ['id'=>'bt_list_add', 'text'=>'添加优秀学生', 'plain'=>'true', 'icon'=>'fa-plus'];
            $formButtonArr[] = array('id'=>'bt_form_add', 'text'=>'增加', 'class'=>'disabled');
            $this->view->setVar('AddEdit', true);


            $formButtonArr[] = array('id'=>'bt_form_edit', 'text'=>'修改', 'class'=>'disabled');
            $this->view->setVar('AddEdit', true);

        if(UserPower::checkUserPower('Res_App_RPackList_Del')){
            $listButtonArr[] = ['id'=>'bt_list_del', 'text'=>'删除', 'plain'=>'true', 'icon'=>'fa-trash'];
        }

        $this->view->setVars([
            'List'          => Template::createList('List', 'Buy_ExcellentStudent', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, true),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
            'Form'          => Template::createForm('Buy_ExcellentStudent'),
            'FormButton'    => Template::createButtonToolBar($formButtonArr)
        ]);
        $this->view->pick('buy/excellentStudent');
    }

    /**
     * #方法说明：获取优秀学生列表数据
     * # Created by zsc
     */
    public function getExcellentStudentAction(){
        $this->view->disable();
        $parameters = [

        ];
        $data = Main::runModelPaginator('\\Admin\\Models\\buy\\ExcellentStudent', $parameters, true);
        $this->response->setJsonContent($data)->send();



    }


    /**
     * #方法说明： 修改学生信息
     * # Created by zsc
     */
    public function modifyExcellentStudentAction(){
        $this->view->disable();
        $this->request->isPost() or die;
        $realData = Main::getRealData($this->request->getPost());
        print_r($realData);exit;
        if(empty($realData['iAppId'])) unset($realData['iAppId']);
        $this->dealAppSavePath($realData);
        $dbRollback = false;
        $this->db->begin();
        $oldApp = XhappStore::getOldApp($realData);
        if($oldApp){
            if($oldApp->sAppVersion != $realData['sAppVersion']){                                           //有记录但版本不同
                self::checkAppOperatePower($realData['iAppType'], true) or die(Main::showMessageModal('无新增权限！', 109101009));
                $oldApp->bAppHistory = 1;
                $oldApp->updateData() or die(Main::showMessageModal('操作失败！', 109101005));
                $app = XhappStore::createRecord(null, $realData, $oldApp);
                if(!$app->updateData()) {                                                      //109101008
                    $dbRollback = true;
                    goto dealTrans;
                }
                if(!$this->insertDroidWallAndRetainByApp($app)){
                    $dbRollback = true;
                    goto dealTrans;
                }
                Main::createCommitLog('app', 'AppStore', 'add', $app, $app->iAppId, '应用版本不同，应用更新');
            }
            else{                                                                                           //有记录且版本相同
                if(isset($realData['Cover']) && $realData['Cover'] == '1'){                                                              //是否确认覆盖
                    self::checkAppOperatePower($realData['iAppType'], false) or die(Main::showMessageModal('无修改权限！', 109101010));
                    $app = XhappStore::createRecord($oldApp->iAppId, $realData);
                    $app->updateData() or die(Main::showMessageModal('操作失败！', 109101006));
                    if(!$this->insertDroidWallAndRetainByApp($app)){
                        $dbRollback = true;
                        goto dealTrans;
                    }
                    Main::createCommitLog('app', 'AppStore', 'edit', $app, $app->iAppId, '应用版本相同，信息覆盖');
                    echo "<script>window.top.createModal('覆盖成功！', '提示', '', 'sm');</script>";
                }
                else{
                    echo "<script>window.top.createModal('检测到该版本已有记录，是否覆盖？', '警告', '覆盖', 'sm', window.parent.confirmCover);</script>";
                    die;
                }
            }
        }
        else{
            self::checkAppOperatePower($realData['iAppType'], true) or die(Main::showMessageModal('无新增权限！', 109101011));
            $app = XhappStore::createRecord(null, $realData);
            $app->insertData() or die(Main::showMessageModal('操作失败！', 109101007));
            if(!$this->insertDroidWallAndRetainByApp($app)){
                $dbRollback = true;
                goto dealTrans;
            }
            Main::createCommitLog('app', 'AppStore', 'add', $app, $app->iAppId, '应用不存在，应用新增');
        }
        dealTrans:
        if($dbRollback) {
            $this->db->rollback();
            die(Main::showMessageModal('操作失败！', 109101008));
        }
        $this->db->commit();
        echo '执行成功！';
    }



    /**
     * 上传资源包并返回相应信息
     *
     * create by ck 20161218
     */
    public function uploadBuyAction()
    {
        set_time_limit(0);
        $this->view->disable();
       $this->request->hasFiles() or die;
        $appParseInfo = Main::getConfigByName('appParse');
        $filePath = $appParseInfo['tempPath'];
        $filePath or $filePath = '/Mailserver/cache/temp/';
        foreach($this->request->getUploadedFiles() as $file){
            $fileName = $file->getName();
            $fileSuffix = explode('.', $fileName);
            $fileSuffix = end($fileSuffix);
            $fullPath = $filePath . time().rand(0,100000).'.'.$fileSuffix;
            $result =  $file->moveTo($fullPath);
            return $result?$fullPath:false;
        }
    }




    /**
     * #方法说明：激活学生列表
     * # Created by zsc
     */
    public function activeStudentAction()
    {
        Assets::easyUI('js/buy/getActiveStudent.js');
        Assets::fileInput();
        Main::showNavPosition();
        $this->view->setVar('NavUl', '<ul class="breadcrumb"><li><i class="fa fa-home fa-lg"></i> 主页</li><li>购买服务</li><li>学生列表</li></ul>');
        $listButtonArr = $formButtonArr = $listSearchArr = array();
        if(UserPower::checkUserPower('Res_App_RPackList_Add')){
            $listButtonArr[] = ['id'=>'bt_list_add', 'text'=>'导入', 'plain'=>'true', 'icon'=>'fa-plus'];
            $formButtonArr[] = ['id'=>'bt_form_add', 'text'=>'增加', 'class'=>'disabled'];
            $this->view->setVar('AddEdit', true);
        }
        if(UserPower::checkUserPower('Res_App_RPackList_Del')){
            $listButtonArr[] = ['id'=>'bt_list_del', 'text'=>'删除', 'plain'=>'true', 'icon'=>'fa-trash'];
        }
        if(UserPower::checkUserPower('Res_App_RPackList_Contact')){

        }

        $this->view->setVars([
            'List'          => Template::createList('List', 'Buy_ActiveStudent', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, true),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
        ]);
        $this->view->pick('buy/activeStudent');
    }

    /**
     * #方法说明：获取学生激活
     * # Created by zsc
     */
    public function getActiveStudentAction(){





    }

}

